﻿
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace CatEars.Text
{
    /// <summary>
    /// 字符串分割合并转义
    /// </summary>
    public class StringCSE
    {
        #region 拆分合并
        /// <summary>
        /// 将集合拼接成字符串
        /// </summary>
        /// <param name="coll">集合</param>
        /// <param name="separator">分隔字符</param>
        /// <param name="ignoreEmpty">忽略空白项</param>
        /// <param name="escapeChar">转义字符</param>
        /// <returns>字符串</returns>
        public static string Combine(
            IEnumerable coll,
            string separator,
            bool ignoreEmpty = false,
            char escapeChar = '\\')
        {
            if (coll == null)
            {
                return string.Empty;
            }
            StringBuilder strCombine = new StringBuilder();
            if (ignoreEmpty)
            {
                foreach (var item in coll)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    string strValue = item.ToString();
                    if (string.IsNullOrEmpty(strValue))
                    {
                        continue;
                    }
                    AppendValueWithEscape(strCombine, strValue, separator, escapeChar);
                    strCombine.Append(separator);
                }
            }
            else
            {
                foreach (var item in coll)
                {
                    if (item == null)
                    {
                        strCombine.Append(escapeChar + "<null>");
                    }
                    else
                    {
                        string strValue = item.ToString();
                        AppendValueWithEscape(strCombine, strValue, separator, escapeChar);
                    }
                    strCombine.Append(separator);
                }
            }
            if (strCombine.Length == 0)
            {
                return string.Empty;
            }
            strCombine.Length--;
            return strCombine.ToString();
        }

        /// <summary>
        /// 将字符串分割为指定类型的集合
        /// </summary>
        /// <param name="value">输入字符串</param>
        /// <param name="separator">分隔字符</param>
        /// <param name="ignoreEmpty">忽略空白项</param>
        /// <param name="needThrowExc">抛出异常</param>
        /// <param name="escapeChar">转义字符</param>
        /// <returns>集合</returns>
        public static IEnumerable<string> Split(string value,
            string separator,
            bool ignoreEmpty = false,
            bool needThrowExc = false,
            char escapeChar = '\\')
        {
            return Split<string>(value, separator, ignoreEmpty, needThrowExc, escapeChar);
        }

        /// <summary>
        /// 将字符串分割为指定类型的集合
        /// </summary>
        /// <param name="value">输入字符串</param>
        /// <param name="separator">分隔字符</param>
        /// <param name="ignoreEmpty">忽略空白项</param>
        /// <param name="needThrowExc">抛出异常</param>
        /// <param name="escapeChar">转义字符</param>
        /// <returns>集合</returns>
        public static IEnumerable<T> Split<T>(string value,
            string separator,
            bool ignoreEmpty = false,
            bool needThrowExc = false,
            char escapeChar = '\\')
        {
            if (string.IsNullOrEmpty(value)) yield break;
            var strArr = SplitWithEscape(value, separator, escapeChar);
            Type targetType = typeof(T);
            if (ignoreEmpty)
            {
                foreach (var item in strArr)
                {
                    if (string.IsNullOrEmpty(item)) continue;
                    T obj;
                    try
                    {
                        obj = (T)Convert.ChangeType(item, targetType);
                    }
                    catch
                    {
                        //忽略转换异常的项
                        if (needThrowExc) throw;
                        else continue;
                    }
                    yield return obj;
                }
            }
            else
            {
                foreach (var item in strArr)
                {
                    if (item == null)
                    {
                        yield return default(T);
                        continue;
                    }
                    T obj;
                    try
                    {
                        obj = (T)Convert.ChangeType(item, targetType);
                    }
                    catch
                    {
                        //忽略转换异常的项
                        if (needThrowExc) throw;
                        else continue;
                    }
                    yield return obj;
                }
            }
        }
        #endregion

        #region 按括号拆分合并

        /// <summary>
        /// 将集合拼接成字符串
        /// </summary>
        /// <param name="coll">集合</param>
        /// <param name="bracketL">左括号</param>
        /// <param name="bracketR">右括号</param>
        /// <param name="ignoreEmpty">忽略空白项</param>
        /// <param name="escapeChar">转义字符</param>
        /// <returns>字符串</returns>
        public static string CombineByBrackets(
            IEnumerable coll,
            string bracketL,
            string bracketR,
            bool ignoreEmpty = false,
            char escapeChar = '\\')
        {
            if (coll == null)
            {
                return string.Empty;
            }
            string separator = bracketR + bracketL;
            return bracketL + Combine(coll, separator, ignoreEmpty, escapeChar) + bracketR;
        }

        /// <summary>
        /// 将字符串分割为指定类型的集合
        /// </summary>
        /// <param name="value">输入字符串</param>
        /// <param name="bracketL">左括号</param>
        /// <param name="bracketR">右括号</param>
        /// <param name="ignoreEmpty">忽略空白项</param>
        /// <param name="needThrowExc">抛出异常</param>
        /// <param name="escapeChar">转义字符</param>
        /// <returns>集合</returns>
        public static IEnumerable<string> SplitByBrackets(string value,
            string bracketL,
            string bracketR,
            bool ignoreEmpty = false,
            bool needThrowExc = false,
            char escapeChar = '\\')
        {
            return SplitByBrackets<string>(value, bracketL, bracketR, ignoreEmpty, needThrowExc, escapeChar);
        }

        /// <summary>
        /// 将字符串分割为指定类型的集合
        /// </summary>
        /// <param name="value">输入字符串</param>
        /// <param name="bracketL">左括号</param>
        /// <param name="bracketR">右括号</param>
        /// <param name="ignoreEmpty">忽略空白项</param>
        /// <param name="needThrowExc">抛出异常</param>
        /// <param name="escapeChar">转义字符</param>
        /// <returns>集合</returns>
        public static IEnumerable<T> SplitByBrackets<T>(string value,
            string bracketL,
            string bracketR,
            bool ignoreEmpty = false,
            bool needThrowExc = false,
            char escapeChar = '\\')
        {
            if (string.IsNullOrEmpty(value)) yield break;
            if (!value.StartsWith(bracketL))
            {
                throw new Exception("输入串必须以“" + bracketL + "”开头");
            }
            if (!value.EndsWith(bracketR))
            {
                throw new Exception("输入串必须以“" + bracketR + "”结尾");
            }
            string separator = bracketR + bracketL;
            value = value.Substring(bracketL.Length, value.Length - separator.Length);
            var strArr = SplitWithEscape(value, separator, escapeChar);
            Type targetType = typeof(T);
            if (ignoreEmpty)
            {
                foreach (var item in strArr)
                {
                    if (string.IsNullOrEmpty(item)) continue;
                    T obj;
                    try
                    {
                        obj = (T)Convert.ChangeType(item, targetType);
                    }
                    catch
                    {
                        //忽略转换异常的项
                        if (needThrowExc) throw;
                        else continue;
                    }
                    yield return obj;
                }
            }
            else
            {
                foreach (var item in strArr)
                {
                    if (item == null)
                    {
                        yield return default(T);
                        continue;
                    }
                    T obj;
                    try
                    {
                        obj = (T)Convert.ChangeType(item, targetType);
                    }
                    catch
                    {
                        //忽略转换异常的项
                        if (needThrowExc) throw;
                        else continue;
                    }
                    yield return obj;
                }
            }
        }

        #endregion

        #region 转义方法

        /// <summary>
        /// 将value进行转义添加到strB中
        /// </summary>
        /// <param name="strB"></param>
        /// <param name="value"></param>
        /// <param name="separator"></param>
        /// <param name="escapeChar"></param>
        static void AppendValueWithEscape(StringBuilder strB,
            string value,
            string separator,
            char escapeChar)
        {
            for (int i = 0; i < value.Length; i++)
            {
                bool blnMatch = ExString.MatchSubString(value, i, separator, 0);
                if (blnMatch)
                {
                    strB.Append(escapeChar);
                    strB.Append(separator);
                    i += separator.Length - 1;
                }
                else
                {
                    strB.Append(value[i]);
                }
            }
        }

        /// <summary>
        /// 按预定义的转义方法还原集合
        /// </summary>
        /// <param name="value"></param>
        /// <param name="separator"></param>
        /// <param name="escapeChar"></param>
        /// <returns></returns>
        static IEnumerable<string> SplitWithEscape(
            string value,
            string separator,
            char escapeChar)
        {
            StringBuilder strBTmp = new StringBuilder();
            for (int i = 0; i < value.Length; i++)
            {
                char chrCurrent = value[i];
                if (chrCurrent == escapeChar)
                {
                    if (ExString.MatchSubString(value, i + 1, separator, 0))
                    {
                        strBTmp.Append(separator);
                        i += separator.Length;
                        continue;
                    }
                    else if (strBTmp.Length == 0
                        && ExString.MatchSubString(value, i + 1, separator + "<null>", 0))
                    {
                        yield return null;
                        i += 6 + separator.Length;
                        continue;
                    }
                    else
                    {
                        throw new FormatException("不支持的转义格式");
                    }
                }
                else if (ExString.MatchSubString(value, i, separator, 0))
                {
                    yield return strBTmp.ToString();
                    strBTmp.Clear();
                    i += separator.Length - 1;
                }
                else
                {
                    strBTmp.Append(chrCurrent);
                }
            }
            yield return strBTmp.ToString();
        }

        #endregion
    }
}
